package com.chinackts.auth.repository.redis;

import com.alibaba.fastjson.JSON;
import com.chinackts.auth.model.ProxyIP;
import com.chinackts.auth.model.ProxyIP_SYT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * @author Lianhong
 * @since 2021/10/28
 */
@Repository
@Slf4j
public class ProxyIPRepository {

    @Resource
    private StringRedisTemplate redisTemplate2;

    private static final String KEY = "proxy-ip";

    /**
     * 获取代理IP
     */
    public ProxyIP getProxyIP() {
        ValueOperations<String, String> ops = this.redisTemplate2.opsForValue();
        String proxyIP = ops.get(KEY);
        if (StringUtils.isEmpty(proxyIP)) return null;
        return JSON.parseObject(proxyIP, ProxyIP.class);
    }

    /**
     * 缓存代理IP
     */
    public void saveProxyIP(ProxyIP proxyIP) {
        ValueOperations<String, String> ops = this.redisTemplate2.opsForValue();
        ops.set(KEY, JSON.toJSONString(proxyIP));
    }

    /**
     * 删除代理IP
     */
    public void deleteProxyIP() {
        Boolean del = this.redisTemplate2.delete(KEY);
        if (Boolean.FALSE.equals(del)) {
            log.error("删除代理IP失败");
        }
    }
}
